package cn.goour.web.sys.controller.settings

import cn.goour.utils.Regex.RegexUtils
import cn.goour.web.base.entity.PageInfo
import cn.goour.web.sys.entity.Admin
import cn.goour.web.sys.service.AdminService
import cn.goour.web.sys.service.LogService
import decrypt
import encrypt
import getAdmin
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.validation.Errors
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import setAdmin
import javax.annotation.PostConstruct
import javax.servlet.http.HttpServletRequest

@Controller
@RequestMapping("/admin/my")
open class MyActionController {

    @Autowired private
    lateinit var adminService: AdminService
    @Autowired private
    lateinit var logService: LogService

    @GetMapping("/info")
    open fun index(): String {
        return "web/admin/my/adminInfo"
    }

    @PostMapping("/info")
    open fun index(admin: Admin, model: Model, request: HttpServletRequest): String {
        val errors = arrayListOf<String>()
        if (!"^[\u4e00-\u9fa5A-Za-z0-9_ ]{2,64}\$".toRegex().matches(admin.name)) {
            errors.add("姓名只能中文、英文和中英组合，长度在2-64之间")
        }
        if (!RegexUtils.isValidEmail(admin.email)) {
            errors.add("电子邮件格式不正确")
        }
        if (errors.isEmpty()) {
            val new = request.getAdmin().copy(name = admin.name, email = admin.email, phone = admin.phone)
            adminService.update(new)
            request.setAdmin(new)
            model.addAttribute("success_info", "数据更新成功")
        } else {
            model.addAttribute("error_info", errors.toString())
        }
        return "web/admin/my/adminInfo"
    }

    @PostMapping("/pass")
    open fun changePassword(password1: String, password2: String, myPassword: String, model: Model, request: HttpServletRequest): String {
        val errors = arrayListOf<String>()
        if (password1 != password2) {
            errors.add("新密码两次输入密码不一致")
        }
        if (password1.isBlank()) {
            errors.add("新密码不能为空")
        }
        if (!"^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}\$".toRegex().matches(password1)) {
            errors.add("密码必须包含大小写字母和数字的组合，不能使用特殊字符，长度在8-16之间")
        }
        if (myPassword != request.getAdmin().password.decrypt()) {
            errors.add("当前用户密码校验失败")
        }
        if (errors.isEmpty()) {
            val admin = request.getAdmin()
            admin.password = password1.encrypt()
            adminService.update(admin)
            model.addAttribute("success_pass", "数据更新成功")
        } else {
            model.addAttribute("error_pass", errors.toString())
        }

        return "web/admin/my/adminInfo"
    }

    @GetMapping("/log")
    open fun log(@Validated pageInfo: PageInfo, errors: Errors, model: Model, request: HttpServletRequest): String {
        if (errors.hasErrors()) {
            pageInfo.page = 1
            pageInfo.size = 10
        }
        val list = logService.getAdminLogs(pageInfo, request.getAdmin().id)
        model.addAttribute("page", list)
        model.addAttribute("pageInfo", pageInfo)

        return "web/admin/my/log"
    }

    @GetMapping("/log/{id}")
    open fun logInfo(@PathVariable("id") id: Int, model: Model, request: HttpServletRequest): String {
        val log = logService.getAdminLogs(id, request.getAdmin())
        model.addAttribute("log", log)
        return "web/admin/my/logInfo"
    }

    init {
        logger.info("Initialized ${this.javaClass.simpleName}...")
    }

    @PostConstruct
    open fun post() {
        logger.info("PostConstruct ${this.javaClass.simpleName}...")
    }

    companion object {
        private val logger = LoggerFactory.getLogger(MyActionController::class.java)
    }
}